#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1.在窗口上设置右键菜单
    // 1) 设置右键菜单策略 ---> 用户自定义右键菜单
    this->setContextMenuPolicy(Qt::CustomContextMenu);
    // 2) 设置菜单项
    this->winMenu = new QMenu;
    this->winMenu->addAction("打开");
    this->winMenu->addAction("关闭");
    QMenu* newMenu =  this->winMenu->addMenu("新建");
    newMenu->addAction("文件");
    newMenu->addAction("文件夹");
    // 3) 设置右键菜单的信号和槽

    // 2.在 listWidget 上设置右键菜单
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    this->listMenu = new QMenu;
    QAction* appendAction = this->listMenu->addAction("追加");
    QAction* insertAction = this->listMenu->addAction("插入");
    QAction* deleteAction = this->listMenu->addAction("删除");

    connect(appendAction, &QAction::triggered, [this](){
        ui->listWidget->addItem("广州");
    });

    connect(insertAction, &QAction::triggered, [this](){
        int index = ui->listWidget->currentRow();
        ui->listWidget->insertItem(index, "杭州");
    });

    connect(deleteAction, &QAction::triggered, [this](){
        QListWidgetItem* item =  ui->listWidget->currentItem();
        ui->listWidget->removeItemWidget(item);
        delete item;
    });
}

Widget::~Widget()
{
    delete ui;
}

// 鼠标右键菜单展示在鼠标旁边
void Widget::on_Widget_customContextMenuRequested(const QPoint &pos)
{
    this->winMenu->exec(QCursor::pos());
}

void Widget::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    this->listMenu->exec(QCursor::pos());
}
